package com.chaos.meta.common;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.fastjson.JSONObject;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

@Slf4j
public class CustomExcelListener extends AnalysisEventListener<Map<Integer, String>>
{
	/**
	 * 每读取1000条做一次处理，然后清理list ，方便内存回收
	 */
	private static final int BATCH_COUNT = 1000;

	private SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");

	private Calendar calendar = Calendar.getInstance();

	//当前任务Id
	private Long taskId;

	//记录数据处理数量
	private Integer totalHandledRow = 0;

	//记录无效数据行数
	private Integer invalidCount = 0;

	private JSONObject progress = new JSONObject();

//	ImporterBulkDto importerBulkDto = null;

	List<String> columns = new ArrayList<>();

	private Long objectId;

    private Long speciId;

	private String token;

	private List<Long> timestamps = new LinkedList<>();

	private Double[][] values = null;
//
//	private SnapshotServiceForWrapper sSnapshotForWrapper;
//
//	private BodyRunningService sBodyRunning;

	private Class<?> objectType;
//
//	public CustomExcelListener(Class<?> clazz, Long speciId, Long objectId, SnapshotServiceForWrapper sSnapshotForWrapper,
//                               BodyRunningService sBodyRunning, Long taskId, String token)
//	{
//		importerBulkDto = new ImporterBulkDto();
//        this.objectType = clazz;
//        this.objectId = objectId;
//        this.speciId = speciId;
//		this.sSnapshotForWrapper = sSnapshotForWrapper;
//		this.sBodyRunning = sBodyRunning;
//		this.taskId = taskId;
//		this.token = token;
//		progress.put("completeFlag", false);
//		progress.put("importMessage", "Importing!");
//		progress.put("successfulCount", 0);
//		progress.put("invalidCount", 0);
//		LocalCacheUtil.put(taskId.toString(), progress);
//		log.info("init CustomExcelListener!");
//	}

	/**
	 * DO： 读数据，从第三行开始读，从第二列读
	 *
	 */
	@Override
	public void invoke(Map<Integer, String> data, AnalysisContext context)
	{
		try {
			if (values == null)
			{
				values = new Double[BATCH_COUNT][columns.size()];
			}

			calendar.setTime(format.parse(data.get(0)));
			timestamps.add(calendar.getTimeInMillis());

			for (int i = 1; i < data.size(); i++)
			{
				double value = Double.parseDouble(data.get(i));
				values[timestamps.size()-1][i-1] = value;
			}

			if (timestamps.size() >= BATCH_COUNT)
			{
//				saveSnapshot(BATCH_COUNT);
			}
		} catch (Exception e) {
			timestamps.remove(timestamps.size()-1);
			invalidCount++;
		}
	}

	/**
	 * DO：读表头(列名), 只读第一行，略过第二行
	 * */
	@Override
	public void invokeHeadMap(Map<Integer, String> headMap, AnalysisContext context)
	{
		//从第二列开始读表头
		if(columns.isEmpty())
		{
			for (int i = 1; i < headMap.size(); i++)
			{
				columns.add(headMap.get(i));
			}
		}
	}

	/**
	 * 捕获异常，中断读取
	 * */
	@Override
	public void onException(Exception exception, AnalysisContext context) throws Exception {
	    // 在上层捕获进行数据回滚
		throw exception;
	}

	/**
	 * 所有数据解析完成了来调用
	 *
	 */
	@SneakyThrows
	@Override
	public void doAfterAllAnalysed(AnalysisContext context)
	{
//        saveSnapshot(timestamps.size());
//	    if (Body.class.equals(objectType))
//        {
//            sBodyRunning.startSpecialistBody(this.objectId, this.token);
//        }
//		progress.put("completeFlag", true);
//		progress.put("importMessage", "SUCCESS!");
//		LocalCacheUtil.put(taskId.toString(), progress);
	}

//	private void saveSnapshot(int rowNum) throws Exception{
//		handle(rowNum, importerBulkDto);
//
//		AvmResult<Boolean> isImported = sSnapshotForWrapper.importHistoryData(importerBulkDto, this.token);
//        timestamps.clear();
//        if (isImported.getResultData())
//        {
//            totalHandledRow += rowNum;
//            progress.put("successfulCount", totalHandledRow);
//            LocalCacheUtil.put(taskId.toString(), progress);
//        }else {
//            exceptionHandel(isImported.getResultMessage());
//        }
//	}
//
//	private void exceptionHandel(String message) throws Exception {
//		progress.put("completeFlag", true);
//		progress.put("importMessage", "Import fail, the detail is:" + message);
//		LocalCacheUtil.put(taskId.toString(), progress);
//		log.error("CustomExcelListener.sSnapshotForWrapper.importHistoryData.saveSnapshot fail, the message is:" + message);
//		throw new Exception();
//	}
//
//    private void handle(int rowNum, ImporterBulkDto importerBulkDto) {
//        importerBulkDto.setBodyId(objectId);
//        importerBulkDto.setSpeciId(speciId);
//		importerBulkDto.setParamTitles(columns.toArray(new String[0]));
//		importerBulkDto.setTimestamps(timestamps.toArray(new Long[0]));
//		importerBulkDto.setValues(Arrays.copyOf(values, rowNum));
//		importerBulkDto.setColumnNum(columns.size());
//		importerBulkDto.setRowNum(rowNum);
//	}
}